import os
from flask import Blueprint, request, jsonify, flash, redirect, url_for
from database import get_db
from flask import current_app

# 创建排放源关联专用Blueprint
inventory_models_bp = Blueprint('inventory_models', __name__, url_prefix='/inventory/models')


@inventory_models_bp.route('/save/<int:inventory_id>', methods=['POST'])
def save_emission_sources(inventory_id):
    db = get_db()
    source_ids = request.form.getlist('source_ids')
    
    try:
        # 先删除已有的关联
        db.execute('DELETE FROM inventory_emission_sources WHERE inventory_id = ?', (inventory_id,))
        
        # 添加新的关联
        for source_id in source_ids:
            facility = request.form.get(f'facility_{source_id}')
            activity_data = request.form.get(f'activity_data_{source_id}')
            value = request.form.get(f'value_{source_id}')
            reporter = request.form.get(f'reporter_{source_id}')
            
            # 验证必填字段
            if not all([facility, activity_data, value, reporter]):
                flash('请填写所有必填字段', 'danger')
                return redirect(url_for('inventory.edit', id=inventory_id))
            
            db.execute(
                'INSERT INTO inventory_emission_sources (inventory_id, emission_source_id, facility, activity_data, value, reporter) '
                'VALUES (?, ?, ?, ?, ?, ?)',
                (inventory_id, source_id, facility, activity_data, value, reporter)
            )
        
        db.commit()
        flash('排放源关联已保存', 'success')
    except Exception as e:
        db.rollback()
        flash(f'保存失败: {str(e)}', 'danger')
    
    return redirect(url_for('inventory.edit', id=inventory_id))

# 删除排放源关联
@inventory_models_bp.route('/remove/<int:inventory_id>', methods=['POST'])
def remove_emission_source(inventory_id):
    db = get_db()
    ies_id = request.form.get('ies_id')
    
    if not ies_id:
        return '缺少排放源关联ID', 400
    
    try:
        # 验证该关联是否属于当前盘查
        check = db.execute(
            'SELECT id FROM inventory_emission_sources WHERE id = ? AND inventory_id = ?',
            (ies_id, inventory_id)
        ).fetchone()
        
        if not check:
            return '排放源关联不存在或无权删除', 403
            
        db.execute('DELETE FROM inventory_emission_sources WHERE id = ?', (ies_id,))
        db.commit()
        return '删除成功', 200
    except Exception as e:
        db.rollback()
        return str(e), 500

# 添加排放源
@inventory_models_bp.route('/add/<int:inventory_id>', methods=['POST'])
def add_emission_source(inventory_id):
    db = get_db()
    model_id = request.form.get('model_id')
    
    if not model_id:
        return '缺少模型ID', 400
    
    try:
        # 检查是否已关联
        existing = db.execute(
            'SELECT id FROM inventory_emission_sources WHERE inventory_id = ? AND emission_source_id = ?',
            (inventory_id, model_id)
        ).fetchone()
        
        if existing:
            return '该排放源已关联', 400
            
        # 添加新关联
        db.execute(
            'INSERT INTO inventory_emission_sources (inventory_id, emission_source_id) VALUES (?, ?)',
            (inventory_id, model_id)
        )
        db.commit()
        return '添加成功', 200
    except Exception as e:
        db.rollback()
        return str(e), 500
# 搜索模型
@inventory_models_bp.route('/search')
def search_models():
    """
    搜索排放源模型
    只返回models表的基本信息
    """
    db = get_db()
    query = request.args.get('query', '')
    
    try:
        models = db.execute(
            '''
            SELECT id, emission_source, description, emission_unit
            FROM models
            WHERE emission_source LIKE ? OR description LIKE ?
            ORDER BY emission_source
            ''',
            (f'%{query}%', f'%{query}%')
        ).fetchall()
        
        return jsonify([dict(model) for model in models])
        
    except Exception as e:
        current_app.logger.error(f"搜索模型失败: {str(e)}")
        return jsonify({'error': '搜索失败，请检查查询条件'}), 500
# 自动关联排放源
@inventory_models_bp.route('/auto_associate/<int:inventory_id>', methods=['POST'])
def auto_associate_sources(inventory_id):
    db = get_db()
    inventory = db.execute('SELECT * FROM carbon_inventory WHERE id = ?', (inventory_id,)).fetchone()
    
    if not inventory or not inventory['model_categories_id']:
        return '没有找到有效的模型分类', 400
    
    try:
        # 使用递归CTE查询所有子分类ID
        category_query = '''
            WITH RECURSIVE category_tree AS (
                SELECT id FROM model_categories WHERE id = ?
                UNION ALL
                SELECT mc.id FROM model_categories mc
                JOIN category_tree ct ON mc.parent_id = ct.id
            )
            SELECT id FROM models WHERE category_id IN (SELECT id FROM category_tree)
        '''
        
        new_models = db.execute(category_query, (inventory['model_categories_id'],)).fetchall()
        
        if new_models:
            for model in new_models:
                existing = db.execute(
                    'SELECT id FROM inventory_emission_sources WHERE inventory_id = ? AND emission_source_id = ?',
                    (inventory_id, model[0])
                ).fetchone()
                
                if not existing:
                    db.execute(
                        'INSERT INTO inventory_emission_sources (inventory_id, emission_source_id, created_at, updated_at) VALUES (?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)',
                        (inventory_id, model[0])
                    )
            db.commit()
            return 'success', 200
        else:
            return '该模型分类及其子分类下没有排放源', 200
    except Exception as e:
        db.rollback()
        return str(e), 500

@inventory_models_bp.route('/edit_factor_by_name', methods=['GET'])
def edit_factor_by_name():
    factor_name = request.args.get('factor_name')
    if not factor_name:
        return '缺少碳排放因子名称', 400
    
    db = get_db()
    try:
        # 在carbon_factors表中查找匹配的因子记录
        factor = db.execute(
            'SELECT id FROM carbon_factors WHERE name = ?', 
            (factor_name,)
        ).fetchone()
        
        if not factor:
            return '未找到匹配的碳排放因子', 404
            
        # 重定向到现有的编辑路由
        return redirect(url_for('factor.edit_factor', id=factor['id']))
    except Exception as e:
        current_app.logger.error(f"查找碳排放因子失败: {str(e)}")
        return str(e), 500

@inventory_models_bp.route('/get_emission_value/<string:factor_name>')
def get_emission_value(factor_name):
    db = get_db()
    
    # 根据碳排放因子名称查询碳排值
    factor = db.execute(
        'SELECT emission_value FROM carbon_factors WHERE name = ?', 
        (factor_name,)
    ).fetchone()
    
    if factor:
        return jsonify({'emission_value': factor['emission_value']})
    else:
        return jsonify({'error': '未找到匹配的碳排放因子'}), 404
